<template>
  <div class="situation">
    <div class="situation-info">
      <!--基本信息-->
      <div class="situation-basic-info">
        <div class="situation-basic-info-title"><span>基本信息</span></div>
        <div class="situation-basic-info-content">
          <div
            v-for="(value, key) in basicInfoDict"
            :key="key"
            class="info-item"
          >
            <div class="info-name">{{ basicInfoDict[key] }}:</div>

            <div v-if="basicInfoDict[key] == '在线状态'" class="info-value">
              {{ basicInfoData[key] ? "在线" : "不在线" }}
            </div>
            <div v-else class="info-value">{{ basicInfoData[key] }}</div>
          </div>
        </div>
      </div>
      <!--设备控制-->
      <div class="situation-device-control">
        <div class="situation-device-control-title">
          <span>设备控制</span>
        </div>
        <div class="btn-content">
          <div class="control-btn">
            <span @click="buildLink">链路开通</span>
          </div>
          <div class="control-btn">
            <span @click="delLink">链路拆除</span>
          </div>
        </div>
        <div class="btn-content">
          <div class="control-btn">
            <span @click="openParamsCfg">开通参数配置</span>
          </div>
          <div class="control-btn">
            <span @click="networkParamsCfg">网络参数配置</span>
          </div>
        </div>
      </div>
      <!--实时业务通信-->
      <div class="situation-device-info">
        <div class="situation-device-video">
          <div class="situation-device-video-title">
            <span>实时业务通信</span>
          </div>
          <div class="btns-container">
            <el-button
              class="btns"
              :disabled="$store.getters.websocket !== null"
              @click="callInit(cScatteringIp)"
            >c设备
            </el-button>
            <el-button
              class="btns"
              :disabled="$store.getters.websocket !== null"
              @click="callInit(kuScatteringIp)"
            >ku设备
            </el-button>
          </div>

          <div class="video-edit">
            <div class="video-title">文字交流</div>
            <div class="video-textarea">
              <span v-for="(item, index) in msgList" :key="index" class="msg">
                {{ item["fromUser"] || "--" }} : {{ item["textMsg"] || "--" }}
                <br>
              </span>
            </div>
            <div class="video-title">
              <el-input v-model="sendMsg" style="flex: 1" />
              <div class="img-flex">
                <!--      音频     -->
                <div class="img-phone">
                  <el-button
                    :disabled="$store.getters.websocket == null"
                    @click="connectTo('1')"
                  >
                    <img
                      src="@/assets/images/situation/phone.png"
                      style="width: 10px; height: 10px"
                      alt=""
                    >
                    音频
                  </el-button>
                </div>
                <!--      视频     -->
                <div class="img-video">
                  <el-button
                    :disabled="$store.getters.websocket == null"
                    @click="connectTo('2')"
                  >
                    <img
                      src="@/assets/images/situation/video.png"
                      style="width: 10px; height: 10px"
                      alt=""
                    >
                    视频
                  </el-button>
                </div>
              </div>
            </div>
            <div class="video-input">
              <div class="sendBtn">
                <el-button
                  :disabled="$store.getters.websocket == null"
                  @click="sendMsgMethod"
                >
                  发送
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="situation-map">
      <Map @queryId="queryId" />
    </div>
  </div>
</template>

<script>
import { queryId, buildLink, delLink } from '@/api/situation'
import Map from '@/views/situation/components/map.vue'
import { WebSocketInit } from '@/api/websocket'
import { getToUser, rtcServerIp } from '@/api/audioVideoApis'
import store from '@/store'

export default {
  name: 'Situation',
  components: { Map },
  data() {
    return {
      username: null,
      toUser: null,
      kuScatteringIp: null,
      cScatteringIp: null,
      sendMsg: null,
      msgList: [],
      // 基本信息
      basicInfoData: {
        createTime: '2024-09-05 06:50:31',
        updateTime: null,
        id: '11001',
        nodeName: 'c频段散射通信设备001', // 设备名称
        nodeType: 'c频段散射通信设备', // 设备类型
        nodeIp: '192.168.3.18', // 设备ip
        online: 1, // 在线状态 0不在 1在线
        lat: '37.55', // 纬度
        lng: '120.44', // 经度
        channel: '1', // 波道号
        xyAxis: ['37.55', '120.44']
      },
      basicInfoDict: {
        nodeName: '设备名称',
        nodeType: '设备类型',
        nodeIp: '设备ip',
        online: '在线状态',
        lat: '经度',
        lng: '纬度',
        channel: '波道号'
      }
    }
  },
  computed: {},
  watch: {
    '$store.getters.websocketContent': {
      handler(val) {
        if (val) {
          console.log('index.vue的websocket监听', val)
          if (val == null) {
            return
          }
          const {
            type,
            fromUser,
            toUser,
            msg,
            sdp,
            iceCandidate,
            callType,
            textMsg
          } = val
          if (type === 'call_start') {
            this.$nextTick(() => {
              this.$router.push({
                path: '/webrtc',
                query: {
                  flag: callType,
                  username: this.username
                }
              })
            })
            return
          }
          if (type === 'text_msg') {
            this.$nextTick(() => {
              this.msgList.push({
                fromUser: fromUser,
                textMsg: textMsg
              })
            })
          }
        }
      }
    },
    '$store.getters.username': {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) {
          console.log('页面内收到username', val)
          this.$nextTick(() => {
            this.username = val
          })
        }
      }
    }
  },
  created() {},
  mounted() {
    // setTimeout(() => {
    // this.$store.commit("websocket/SET_WEBSOCKET_CONNECT", {
    //   type: "text_msg", //消息类型 text_msg hangup call_start call_back offer answer _ice
    //   callType: "-", //通话类型
    //   fromUser: "zdh", //发起用户
    //   toUser: "-", //接受用户
    //   msg: "-", //控制消息
    //   sdp: "-", //sdp
    //   iceCandidate: "-", //iceCandidate
    //   textMsg: "555555555", //文字消息
    // });
    console.log('wwwwwwwww', this.$store.getters.websocket)
    // }, 3000);
    // this.initUrl();
    // this.startWebSocket();
    this.rtcServerIpMethod()
  },
  methods: {
    // 获取RTC服务端IP
    rtcServerIpMethod() {
      rtcServerIp().then((res) => {
        if (res.code == 200) {
          this.kuScatteringIp = res.data['kuScatteringIp']
          this.cScatteringIp = res.data['cScatteringIp']
        }
      })
    },
    // 获取对端ws用户名称
    getToUserMethod() {
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          getToUser(this.username)
            .then((res) => {
              if (res.code == 200) {
                this.toUser = res.data
                resolve()
                return
              }
            })
            .catch((err) => {
              reject(new Error('获取用户失败'))
              return
            })
        })
      })
    },
    // 建链
    async callInit(ip) {
      if (this.username == null) {
        this.username = await this.generateRandomLetters(2)
        this.$store.commit('websocket/SET_WEBSOCKET_USERNAME', this.username)
      }
      this.$nextTick(() => {
        WebSocketInit(ip, this.username)
      })
    },
    generateRandomLetters(length) {
      let result = ''
      const characters = 'abcdefghijklmnopqrstuvwxyz' // 字母表

      for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length)
        const randomLetter = characters[randomIndex]
        result += randomLetter
      }

      return result
    },
    // 基本信息查询
    queryId(id) {
      queryId(id)
        .then((res) => {
          const data = res.data.data
          const msg = res.data.msg
          if (msg == '成功') {
            // this.$message.success("基本信息查询" + msg);
          } else {
            this.$message.error('基本信息查询' + msg)
          }
          if (data != null) {
            this.basicInfoData = data
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 链路开通
    buildLink() {
      buildLink(this.basicInfoData.id)
        .then((res) => {
          const data = res.data.data
          const msg = res.data.msg
          if (msg == '成功') {
            // this.$message.success("链路开通" + msg);
          } else {
            this.$message.error('链路开通' + msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 链路拆除
    delLink() {
      delLink(this.basicInfoData.id)
        .then((res) => {
          const data = res.data.data
          const msg = res.data.msg
          if (msg == '成功') {
            // this.$message.success("链路拆除" + msg);
          } else {
            this.$message.error('链路拆除' + msg)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    openParamsCfg() {},
    networkParamsCfg() {},
    // -------------webrtc相关开始--------------
    // 初始化各种url
    initUrl() {
      const wsProtocol = document.location.protocol == 'https:' ? 'wss' : 'ws'
      this.chatWebSocketUrl =
        wsProtocol + '://' + this.url + '/webrtc/onlineUserControl'
      this.websocketUrl = this.chatWebSocketUrl + '?user=' + this.username
    },
    // websocket连接
    startWebSocket() {
      const self = this // 保存Vue实例的引用
      // 创建websocket实例
      if ('WebSocket' in window) {
        try {
          this.webSocket = new WebSocket(this.websocketUrl)
        } catch (e) {
          console.log(e)
        }
      } else if ('MozWebSocket' in window) {
        this.webSocket = new MozWebSocket(this.websocketUrl)
      } else {
        console.log('not support')
      }
      this.webSocket.onmessage = function(returnMessage) {
        // 消息接收
        console.log(returnMessage)
        const message = JSON.parse(returnMessage.data)
        console.log(message.type)
        if (message.type == 'get_online_user') {
          // 获取在线用户列表
          const users = message.list
          for (let i = 0; i < users.length; i++) {
            if (users[i] == 'xu' || users[i] == 'xunan') {
              continue
            } else {
              const userObj = { name: users[i], ip: '192.168.3.' + i }
              self.userList.push(userObj)
            }
          }
        }
      }
    },
    async connectTo(flag) {
      this.$store.commit('websocket/SET_WEBSOCKET_CONNECT', null) // 清空存的ws信息

      await this.getToUserMethod()
      this.$nextTick(() => {
        this.$router.push({
          path: '/webrtc',
          query: {
            flag: flag,
            username: this.username,
            toUser: this.toUser,
            call: true
          }
        })
      })
    },
    // 发送文字消息
    async sendMsgMethod() {
      this.$store.commit('websocket/SET_WEBSOCKET_CONNECT', null) // 清空存的ws信息

      this.msgList.push({
        fromUser: this.username,
        textMsg: this.sendMsg
      })
      await this.getToUserMethod()
      this.$nextTick(() => {
        this.$store.getters.websocket.send(
          JSON.stringify({
            type: 'text_msg',
            fromUser: this.username,
            toUser: this.toUser,
            textMsg: this.sendMsg
          })
        )
      })
    },
    getToken() {
      return Math.round(Math.random() * 9999999999) + 9999999999
    }
    // -------------webrtc相关结束--------------
  }
}
</script>

<style lang="scss" scoped>
.situation {
  display: flex;
  height: 100%;
  padding: 14px;

  .situation-info {
    width: 21.875rem;
    display: flex;
    flex-direction: column;
    margin-right: 1rem;

    .situation-basic-info {
      height: 17.5rem;
      background: url("~@/assets/images/situation/basicInfo-background.png")
        no-repeat center center;
      background-size: 100% 100%;
      display: flex;
      flex-direction: column;
      padding: 0.5rem;

      .situation-basic-info-title {
        background: url("~@/assets/images/situation/title-border.png") no-repeat
          center center;
        background-size: 100% 100%;
        height: 2.8125rem;
        line-height: 2.8125rem;

        span {
          padding-left: 3.75rem;
          font-weight: bold;
          background: linear-gradient(to bottom, #f0f0f0, #00e4ff);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          letter-spacing: 0.15em;
        }
      }

      .situation-basic-info-content {
        flex: 1;
        display: flex;
        flex-direction: column;

        .info-item {
          display: flex;
          flex-direction: row;
          padding: 0.2rem 0.5rem;
          font-size: 1rem;
          flex: 1;

          .info-name {
            width: 6.25rem;
            font-weight: 400;
            color: #00caff;
            text-align: right;
            padding-right: 0.8rem;
          }

          .info-value {
            flex: 1;
            color: #ccf4ff;
          }
        }
      }
    }

    .situation-device-control {
      height: 12.5rem;
      padding: 0.5rem;
      display: flex;
      flex-direction: column;
      background: url("~@/assets/images/situation/basicInfo-background.png")
        no-repeat center center;
      background-size: 100% 100%;
      margin: 1rem 0;

      .situation-device-control-title {
        background: url("~@/assets/images/situation/title-border.png") no-repeat
          center center;
        background-size: 100% 100%;
        height: 2.1875rem;
        line-height: 2.1875rem;

        span {
          padding-left: 3.75rem;
          font-weight: bold;
          background: linear-gradient(to bottom, #f0f0f0, #00e4ff);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          letter-spacing: 0.15em;
        }
      }

      .btn-content {
        flex: 1;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        margin-top: 0.5rem;

        .control-btn {
          :hover {
            color: #1adafb;
          }

          span {
            display: inline-block;
            text-align: center;
            margin-left: 0.625rem;
            width: 9rem;
            height: 3rem;
            line-height: 3rem;
            background: url("~@/assets/images/taskArrangement/search-button.png")
              no-repeat center center;
            background-size: 100% 100%;
            cursor: pointer;
          }
        }
      }
    }

    .situation-device-info {
      flex: 1;
      background-color: #fff;
      background: url("~@/assets/images/situation/deviceInfo-background.png")
        no-repeat center center;
      background-size: 100% 100%;
      display: flex;
      flex-direction: column;

      .situation-device-video {
        flex: 1;
        padding: 0.5rem;
        display: flex;
        flex-direction: column;

        .btns-container {
          display: flex;
          justify-content: center;
          padding: 0 0 10px 0;

          .btns {
            width: 100px !important;
            display: inline-block;
          }
        }

        .situation-device-video-title {
          background: url("~@/assets/images/situation/title-border.png")
            no-repeat center center;
          background-size: 100% 100%;
          height: 2.1875rem;
          line-height: 2.1875rem;
          margin-bottom: 1rem;

          span {
            padding-left: 3.75rem;
            font-weight: bold;
            background: linear-gradient(to bottom, #f0f0f0, #00e4ff);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            letter-spacing: 0.15em;
          }
        }

        .video-edit {
          flex: 1;
          height: 0;
          display: flex;
          flex-direction: column;
          background-color: #08133e;

          .video-title {
            height: 3rem;
            line-height: 2rem;
            font-size: 1rem;
            background: url("~@/assets/images/situation/video_text.png")
              no-repeat center center;
            background-size: 100% 100%;
            color: #97e9ff;
            padding-left: 0.625rem;
            display: flex;
            flex-direction: row;
            align-items: center;

            .img-flex {
              height: 0;
              flex: 0.5;
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: flex-end;

              img {
                width: 100%;
                height: 100%;
                cursor: pointer;
              }

              .img-video {
                margin: 0 0.625rem;
              }
            }
          }

          .video-textarea {
            flex: 2;
            height: 0;
            overflow: auto;
          }

          .video-input {
            height: 0;
            flex: 1;
            position: relative;

            .sendBtn {
              position: absolute;
              right: 0;
              bottom: 0;

              :hover {
                color: #1adafb;
              }

              span {
                display: inline-block;
                text-align: center;
                margin-left: 0.625rem;
                width: 4rem;
                height: 2rem;
                line-height: 2rem;
                background: url("~@/assets/images/taskArrangement/search-button.png")
                  no-repeat center center;
                background-size: 100% 100%;
                font-size: 1rem;
                cursor: pointer;
              }
            }
          }
        }
      }
    }
  }

  .situation-map {
    flex: 1;
    background: url("~@/assets/images/situation/map-border.png") no-repeat
      center center;
    background-size: 100% 100%;
    padding: 20px;
  }
}
</style>
